<template>
  <el-form class="demo-ruleForm" :model="ruleForm" :rules="rules" ref="ruleForm" status-icon>
    <!-- 手机号 -->
    <el-form-item label="" prop="phone">
      <el-input placeholder="请输入手机号" v-model.number="ruleForm.phone" autocomplete="off" clearable></el-input>
    </el-form-item>
    <!-- 验证码 -->
    <el-form-item label="" prop="code">
      <el-input placeholder="请输入验证码" v-model="ruleForm.code" autocomplete="off">
        <template slot="append"><span @click="getCode('ruleForm')" class="get-code">获取验证码</span></template>
      </el-input>
    </el-form-item>
    <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">登 录</el-button>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      ruleForm: {
        phone: '',
        code: '',
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { required: true, pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, trigger: 'blur', message: '请输入正确的手机号格式' },
        ],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
      },
    };
  },
  methods: {
    //获取验证码
    getCode(ruleForm) {
      this.$refs[ruleForm].validateField('phone', (valid) => {
        //效验通过发送验证码
        if (!valid) {
          //获取验证码
          this.$request('/captcha/sent', { phone: this.ruleForm.phone });
          //倒计时
          this.backTime();
        } else {
          return false;
        }
      });
    },
    //倒计时函数
    backTime() {
      let code = document.getElementsByClassName('get-code')[0];
      let count = 60;
      let timer = setInterval(() => {
        count--;
        code.innerHTML = count + 's';
        if (count == 0) {
          clearInterval(timer);
          code.innerHTML = '重新获取验证码';
        }
      }, 1000);
    },
    //登录点击
    submitForm(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        //验证通过发送登录请求
        if (valid) {
          this.loading = true;
          let data = {
            phone: this.ruleForm.phone,
            captcha: this.ruleForm.code,
            timestamp: Date.now(),
          };
          //调用登录请求
          this.goLogin(data);
        } else {
          return false;
        }
      });
    },
    //登录请求
    async goLogin(data) {
      let res = await this.$request('/login/cellphone', data);
      if (res.code === 200) {
        //获取账户信息
        this.$store.dispatch('getAccount');
      }
    },
  },
};
</script>

<style  scoped>
.get-code {
  cursor: pointer;
}
.el-button {
  width: 100%;
}
</style>